from rest_framework import serializers
from .models import Category, Tag, Book, BookImage, BookReview


class CategorySerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    
    class Meta:
        model = Category
        fields = ['id', 'name', 'slug', 'parent', 'level', 'description', 'image', 'children']
    
    def get_children(self, obj):
        if obj.children.exists():
            return CategorySerializer(obj.children.all(), many=True).data
        return []


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['id', 'name', 'slug', 'color']


class BookImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookImage
        fields = ['id', 'image', 'alt_text', 'is_main', 'sort_order']


class BookListSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True, read_only=True)
    tags = TagSerializer(many=True, read_only=True)
    main_image = serializers.SerializerMethodField()
    average_rating = serializers.FloatField(read_only=True)
    review_count = serializers.IntegerField(read_only=True)
    
    class Meta:
        model = Book
        fields = [
            'id', 'title', 'slug', 'author', 'publisher', 'isbn',
            'price', 'discount_price', 'stock_quantity', 'cover_image',
            'main_image', 'categories', 'tags', 'average_rating', 
            'review_count', 'is_active', 'is_featured', 'created_at'
        ]
    
    def get_main_image(self, obj):
        main_image = obj.images.filter(is_main=True).first()
        if main_image:
            return BookImageSerializer(main_image).data
        return None


class BookDetailSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True, read_only=True)
    tags = TagSerializer(many=True, read_only=True)
    images = BookImageSerializer(many=True, read_only=True)
    average_rating = serializers.FloatField(read_only=True)
    review_count = serializers.IntegerField(read_only=True)
    
    class Meta:
        model = Book
        fields = [
            'id', 'title', 'slug', 'author', 'publisher', 'isbn',
            'price', 'discount_price', 'stock_quantity', 'min_stock_alert',
            'description', 'content', 'cover_image', 'preview_url',
            'categories', 'tags', 'images', 'average_rating', 'review_count',
            'meta_title', 'meta_description', 'meta_keywords',
            'is_active', 'is_featured', 'sort_order', 'created_at', 'updated_at'
        ]


class BookCreateUpdateSerializer(serializers.ModelSerializer):
    categories = serializers.PrimaryKeyRelatedField(
        many=True, 
        queryset=Category.objects.filter(is_active=True)
    )
    tags = serializers.PrimaryKeyRelatedField(
        many=True, 
        queryset=Tag.objects.all(),
        required=False
    )
    
    class Meta:
        model = Book
        fields = [
            'title', 'author', 'publisher', 'isbn', 'price', 'discount_price',
            'stock_quantity', 'min_stock_alert', 'description', 'content',
            'cover_image', 'preview_url', 'categories', 'tags',
            'meta_title', 'meta_description', 'meta_keywords',
            'is_active', 'is_featured', 'sort_order'
        ]
    
    def create(self, validated_data):
        categories = validated_data.pop('categories', [])
        tags = validated_data.pop('tags', [])
        
        book = Book.objects.create(**validated_data)
        book.categories.set(categories)
        book.tags.set(tags)
        
        return book
    
    def update(self, instance, validated_data):
        categories = validated_data.pop('categories', None)
        tags = validated_data.pop('tags', None)
        
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        if categories is not None:
            instance.categories.set(categories)
        if tags is not None:
            instance.tags.set(tags)
        
        return instance


class BookReviewSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)
    
    class Meta:
        model = BookReview
        fields = ['id', 'user', 'title', 'content', 'rating', 'is_verified', 'created_at']
        read_only_fields = ['id', 'user', 'is_verified', 'created_at']
    
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class BookReviewAdminSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)
    book = serializers.StringRelatedField(read_only=True)
    
    class Meta:
        model = BookReview
        fields = ['id', 'book', 'user', 'title', 'content', 'rating', 
                 'is_approved', 'is_verified', 'created_at']
        read_only_fields = ['id', 'book', 'user', 'created_at']
